package com.qdlc.p2p.biz.service.lottery;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.log.score.BaseScoreLog;
import com.qdlc.p2p.biz.log.score.lottery.ScoreLotteryWinningLog;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.biz.service.NewActivityPlanService;
import com.qdlc.p2p.biz.service.NewActivityRuleService;
import com.qdlc.p2p.biz.service.UserSignService;
import com.qdlc.p2p.biz.util.ActivityTools;
import com.qdlc.p2p.biz.zdata.LotteryResult;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.LotteryCategory;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.util.BeanCopierUtils;
import com.qdlc.p2p.common.util.BeanUtil;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.dao.AdditionalDrawLotteryRuleDao;
import com.qdlc.p2p.dal.dao.LotteryRecordDao;
import com.qdlc.p2p.dal.dto.AdditionalDrawLotteryRule;
import com.qdlc.p2p.dal.dto.LotteryRecord;
import com.qdlc.p2p.dal.dto.NewActivityPlan;
import com.qdlc.p2p.dal.dto.NewActivityRule;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserSign;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * Created by hongbl on 2016/2/2.
 * 将抽奖队列执行的方法放置在此类中
 */
@Service("lotteryTaskService")
public class LotteryTaskServiceImpl implements LotteryTaskService {

    @Resource
    private LotteryRecordDao lotteryRecordDao;
    @Resource
    private UserSignService userSignService;
    @Resource
    private NewActivityPlanService newActivityPlanService;
    @Resource
    private NewActivityRuleService newActivityRuleService;
    @Resource
    private AdditionalDrawLotteryRuleDao additionalDrawLotteryRuleDao;
    @Resource
    @Qualifier("lotteryCollectService")
    private CollectPayService collectService;

    private Logger logger = Logger.getLogger(LotteryTaskServiceImpl.class);

    /**
     * 赠送积分
     *
     * @param userId
     * @param value
     */
    public void giveScore(long userId, double value) {
        //会员积分记录信息 更新积分， 更新日志信息
        Global.setTransfer("score", value);
        BaseScoreLog bLog = new ScoreLotteryWinningLog(userId, (int) value);
        bLog.doEvent();
    }

    /**
     * 赠送现金
     */
    public void giveCash(User user, double money, byte lotteryType) {
        //记录日志
        logger.info("抽中现金开始请求新浪，用户三方账户：" + UserUtils.getUserTppCustId(user.getUserId()));

        TppTradeLog tppTradeLog = collectService.createOrder(lotteryType,user.getUserId(),money);
        ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
        if (returnResult.isError()) {
            logger.info("抽奖兑现失败，用户三方账户：" + UserUtils.getUserTppCustId(user.getUserId()));
        }
    }

    /**
     * 保存中奖日志
     */
    public void saveLotteryLog(LotteryResult result, long userId) {
        // 记录抽奖结果Log
        LotteryRecord lotteryRecord = new LotteryRecord();
        BeanCopierUtils.copyProperties(result, lotteryRecord);
        lotteryRecord.setCategory(LotteryCategory.SIGN.getCategory());
        lotteryRecord.setUserId(userId);
        if (result.getItemId() > 0)
            lotteryRecord.setItemId(result.getItemId());
        lotteryRecord.setAddTime(DateUtil.getNow());
        lotteryRecordDao.save(lotteryRecord);
    }


    /**
     * 记录用户签到
     *
     * @param user
     * @param signDayCount
     */
    public void recordUserSign(User user, int signDayCount, String ip) {
        UserSign userSign = new UserSign();
        userSign.setSignIp(ip);
        userSign.setAddTime(new Date());
        userSign.setSignDayCount(signDayCount);
        userSign.setSignTime(new Date());
        userSign.setDescription("用户签到");
        userSign.setUserId(user.getUserId());
        userSignService.save(userSign);
    }

    /**
     * 签到活动
     *
     * @param userId
     * @param type
     * @return
     */
    public void signActivityPlan(long userId, String type, User user) {
        NewActivityPlan activityPlan = newActivityPlanService.getActivityPlanByTache(type);
        // 校验本活动是否可用
        boolean isAvailable = ActivityTools.checkActivity(activityPlan, userId);
        if (!isAvailable) return;
        //查询活动规则表，如果为空直接返回
        List<NewActivityRule> list = newActivityRuleService.findByActivityId(activityPlan.getId());
        if (null == list || list.isEmpty()) return;
        for (NewActivityRule entity : list) {
            // 校验本条规则是否可用
            if (!ActivityTools.checkRule(entity, userId)) continue;
            String serviceBeanName = entity.getBusinessClass();
            if (serviceBeanName.equals("giveUserLotteryService")) {
                // 判断规则存在+判断状态 0:启用 1:未启用
                AdditionalDrawLotteryRule additionalDrawLotteryRule = additionalDrawLotteryRuleDao.find(entity.getRuleId());
                if (additionalDrawLotteryRule == null || additionalDrawLotteryRule.getStatus() != 0) continue;
                //抽奖规则不满足条件的过滤掉
                UserSign userSign = userSignService.findLastRecord(userId);
                int continueCount = additionalDrawLotteryRule.getContinueCount();
                //如果规定连续动作为1每次都送，如果规定连续动作大于1就需要签到天数=连续动作
                if (continueCount > 1 && (userSign.getSignDayCount() != continueCount)) continue;
            }
            BaseGiveAwardService baseGiveAwardService = (BaseGiveAwardService) BeanUtil.getBean(serviceBeanName);
            BaseGiveAwardModel baseGiveAwardModel = new BaseGiveAwardModel();
            baseGiveAwardModel.setUser(user);
            baseGiveAwardModel.setRuleId(entity.getRuleId());
            baseGiveAwardModel.setSourceType(type);
            baseGiveAwardModel.setRuleType(entity.getType());
            baseGiveAwardModel.setDescription("签到活动");
            baseGiveAwardService.giveAward(baseGiveAwardModel);
        }
    }
}
